package com.wzk.travelspringboot.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.wzk.travelspringboot.common.LogToFile;
import com.wzk.travelspringboot.service.impl.BlogServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author wangzikang
 */
//二维码生成
@Component
@RequiredArgsConstructor
public class TDCodeUtil {

    private final MinioUtil minioUtil;

    public static final Logger logger = Logger.getLogger(TDCodeUtil.class.getName());

    //根据订单号生成二维码
    public String getTCode(String orderNumber){
        try {
            // 设置二维码的宽度和高度
            int width = 150;
            int height = 150;

            // 设置二维码的属性
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);  // 设置二维码的边距
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 设置纠错等级

            // 创建二维码的BitMatrix
            BitMatrix bitMatrix = new MultiFormatWriter().encode(orderNumber, BarcodeFormat.QR_CODE, width, height, hints);

            // 创建BufferedImage对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }
            //转换成inpStream
            InputStream qrCodeInputStream = bufferedImageToInputStream(image);
            //保存到minio返回保存路径
            String codeUrl = minioUtil.uploadImageFile("code", orderNumber + ".png", qrCodeInputStream);
            return codeUrl;
        } catch (Exception e) {
            LogToFile.logToFile("生成二维码失败！订单号：【"+orderNumber+"】,异常信息："+e,logger,"td_code_err");
            throw new RuntimeException(e);
        }
    }

    // 将 BufferedImage 转换为 InputStream
    private InputStream bufferedImageToInputStream(BufferedImage image) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", byteArrayOutputStream);
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }

}
